﻿using System;
using System.Diagnostics;
using System.Dynamic;
using Xunit;

namespace MyDemo.Dynamic
{
    /// <summary>
    /// DynamicObject示例
    /// </summary>
    public class DynamicObjectSamples
    {
        [Fact]
        public static void Test()
        {
            dynamic dynamicObj = new DynamicType();
            //
            int a = dynamicObj.CallMethod1();
            Console.WriteLine("CallMethod1返回结果：" + a);
            int b = dynamicObj.CallMethod2();
            Console.WriteLine("CallMethod2返回结果：" + b);
            //
            dynamicObj.Name = "Learnig Hard";
            dynamicObj.Age = 24;
        }

        /// <summary>
        /// 继承自DynamicObject类型的类
        /// </summary>
        private class DynamicType : DynamicObject
        {
            public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
            {
                Console.WriteLine(binder.Name + "方法正在被调用");
                if (binder.Name == "CallMethod1")
                {
                    result = 1;
                }
                else
                {
                    result = 2;
                }
     
                return true;
            }

            public override bool TrySetMember(SetMemberBinder binder, object value)
            {
                Console.WriteLine(binder.Name + " 属性被设置，" + "设置的值为：" + value);
                return true;
            }
        }
    }
}